package org.jeecg.modules.xxgx.fpgl.eventListener;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.constant.enums.MessageTypeEnum;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.modules.innerApi.common.requestDto.InvoiceParam;
import org.jeecg.modules.innerApi.common.responseDto.InvoiceRtn;
import org.jeecg.modules.task.entity.CsPtTask;
import org.jeecg.modules.task.entity.CsPtTaskmx;
import org.jeecg.modules.task.enums.TaskStateEnum;
import org.jeecg.modules.task.service.ICsPtTaskService;
import org.jeecg.modules.task.service.ICsPtTaskmxService;
import org.jeecg.modules.xxgx.djgl.vo.CsXxDkdjPage;
import org.jeecg.modules.xxgx.fpgl.event.BatchInvoiceEvent;
import org.jeecg.modules.xxgx.fpgl.event.vo.BatchInvoiceEventVo;
import org.jeecg.modules.xxgx.fpgl.service.IFpkjglService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 批量开票事件监听器
 */
@Component
@Slf4j
public class BatchInvoiceEventListener {

    @Autowired
    private IFpkjglService fpkjglService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private ICsPtTaskService taskService;
    @Autowired
    private ICsPtTaskmxService taskmxService;

    @Async
    @EventListener
    public void BatchInvoiceEvent(BatchInvoiceEvent event) {
        String id = "";
        BatchInvoiceEventVo eventVo=(BatchInvoiceEventVo)event.getSource();
        log.debug("批量开票任务参数", eventVo.getInvoiceParamList());
        CsPtTask task=eventVo.getTask();
        //设置当前任务线程中的租户信息
        TenantContext.setTenant(task.getTenantId().toString());
        //任务明细:key：fromid+ywid
        Map<String,CsPtTaskmx> taskmxs=eventVo.getTaskmxs();
        //待开单据：key:发票申请流水号
        Map<String,CsXxDkdjPage> dkdjpages=eventVo.getDkdjpages();
        //待开发票
        List<InvoiceParam> invoiceParamList=eventVo.getInvoiceParamList();
        //执行批量开票任务
        //更新主任务为执行中
        task.setState(TaskStateEnum.zxz.getValue());
        taskService.updateById(task);
        String msg="";
        Integer error=0;
        for (int i=0;i<invoiceParamList.size();i++){
            InvoiceParam invoiceParam = invoiceParamList.get(i);
            Result<InvoiceRtn.InvoiceRtnData> rtnData= fpkjglService.invoice(invoiceParam);
            log.info("批量开票返回参数",rtnData);
            //根据发票申请流水号查询待开单据信息
            CsXxDkdjPage dkdjPage=dkdjpages.get(invoiceParam.getFpsqlsh());
            CsPtTaskmx taskmx=taskmxs.get(task.getId()+dkdjPage.getId());
            taskmx.setResult(JSONObject.toJSONString(rtnData));
            taskmx.setRtndesc(rtnData.getMessage());
            if(!rtnData.isSuccess()){
                //更新子任务状态
                taskmx.setState(TaskStateEnum.zxsb.getValue());
                //组装任务失败描述
                msg+="单据编号："+invoiceParam.getFpsqlsh()+"开票失败："+rtnData.getMessage()+"<br>";
                error++;
            }else{
                taskmx.setState(TaskStateEnum.zxcg.getValue());
            }
            //更新子任务状态
            taskmxService.updateById(taskmx);
        }
        //更新主任务状态
        task.setState(TaskStateEnum.zxwb.getValue());
        taskService.updateById(task);
        MessageDTO me=new MessageDTO();
        me.setFromUser(task.getCreateBy());
        me.setToUser(task.getCreateBy());
        me.setTitle("任务编号："+task.getId()+"批量开票执行完成通知");
        me.setType(MessageTypeEnum.XT.getType());
        Integer total=invoiceParamList.size();
        Integer success=total-error;
        if(error==0){
            me.setContent("本次提交开票单据数量："+total+"个；"+"已开票成功："+total+"个");
        }
        if(error>0&&error<=total){
            me.setContent("本次提交开票单据数量："+total+"个；"+"已开票成功："+success+"个；"+"开票失败："+error+"个</br>"
                    +"开票失败原因："+msg);
        }
        sysBaseAPI.sendSysAnnouncement(me);

    }
}
